#include <func.h>

int main(int argc, char* argv[])
{

    int socket_fd = socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi("8080"));
    sockaddr.sin_addr.s_addr = inet_addr("192.168.44.128");

    connect(socket_fd,(struct sockaddr*)&sockaddr,sizeof(sockaddr));

    //首先接收文件名字
    int file_name_len=0;
    recv(socket_fd,&file_name_len,sizeof(int),MSG_WAITALL);
    printf("file_name_len:%d\n",file_name_len);

    char file_name[60]={0};
    recv(socket_fd,file_name,file_name_len,MSG_WAITALL);
    printf("file_name:%s\n",file_name);


    //接收文件长度
    off_t file_length=0;
    int f_len = recv(socket_fd,&file_length,sizeof(off_t),MSG_WAITALL);
    printf("file_length:%d\n",file_length);

    int file_fd = open(file_name,O_RDWR | O_CREAT,0600); 

    //开始循环接收数据
    off_t bytes_received = 0; // 已接收的总字节数
    while(1){
        //每次结收发送来的字节数
        int ret_read=0;
        int r_read = recv(socket_fd,&ret_read,sizeof(int),MSG_WAITALL);
        if(r_read==0){
            break;
        }
        if(ret_read!=1000){
            printf("ret_read:%d\n",ret_read);
        }

        char buf[1000] = {0};
        int ret_recv = recv(socket_fd,buf,ret_read,MSG_WAITALL);
        if(ret_recv==0){
            break;
        }
        bytes_received += ret_recv;
        // 打印进度条  
        printf("\rProgress: %.2lf%% (%lld/%lld)", (float)((bytes_received * 100) / file_length), (long long)bytes_received, (long long)file_length); 
        fflush(stdout);
        sleep(0.01);
        write(file_fd,buf,ret_read);

    }
    printf("\n");
    close(file_fd);
    close(socket_fd);
    return 0;
}

/* // 读取文件名
   int file_name_len=0;
   recv(socket_fd, &file_name_len, sizeof(int), 0);
   printf("file_name_len:%d",file_name_len);

   char file_name[60]={0};
   recv(socket_fd, file_name, file_name_len, 0);

// 收文件大小
off_t file_size =0;
recv(socket_fd, &file_size, sizeof(file_size), MSG_WAITALL);
printf("file_size: %ld \n", file_size);

int file_fd = open(file_name, O_RDWR|O_CREAT, 0600);

// 读取文件内容
while(1){
int buf_len=0;
int ret = recv(socket_fd, &buf_len, sizeof(int), MSG_WAITALL);
if(ret == 0){
break;
}
if(buf_len != 1000){
printf("buf_len: %d \n", buf_len);
}
char buf[1000]={0};
ret = recv(socket_fd, buf, buf_len, MSG_WAITALL);
if(ret == 0){
break;
}

printf("\r 0.5 ");
fflush(stdout);
sleep(1);
printf("\r 0.6 ");
fflush(stdout);
sleep(1);


write(file_fd, buf, buf_len);
}
}*/
